package com.paic.mario.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.paic.mario.dao.SystemMapper;
import com.paic.mario.service.TempletService;

import net.sf.json.JSONObject;
import sun.misc.BASE64Decoder;

@Service
public class TempletServiceImpl implements TempletService{
	  
	private static Logger logger=LoggerFactory.getLogger(TempletServiceImpl.class);
	
		@Autowired
		private SystemMapper systemMapper;

        /**
         * 多服务单模板生成json配置下发功能
         */
		@SuppressWarnings({ "unchecked", "rawtypes" })
		@Override
		public List<Map<String, Object>> saveAndloadTemplet(int templet_id, String flag,List<Map> service_map_list) {
			//
			List<Map<String, Object>> return_list = new ArrayList<Map<String, Object>>();
			
			for(int i = 0 ; i<service_map_list.size(); i++){
				//String host_name = "SZB-L0045555";
				String host_name = service_map_list.get(i).get("host_name").toString();
				String file_name = service_map_list.get(i).get("file_name").toString();
				String service_id = service_map_list.get(i).get("service_id").toString();				
				String param = service_map_list.get(i).get("content").toString();

				//必须有的三个参数,filename,indextemplateid,host_name
				//{  "msg": "success",  "status": 0,  "data": null}
				
				//调用agent的下发接口
				JSONObject json_returnStr = saveAndload(host_name, file_name, flag, param);
				
				if(!"success".equals(json_returnStr.get("msg"))){
					Map map = new HashMap();
					map.put("flag", "error");
					map.put("msg", json_returnStr.get("msg"));
					map.put("service_id", service_id);
					return_list.add(map);
				}
			}
			
			return return_list;
		}
	
		/**
		 * 回写到templetConfig表中
		 * @param service_id
		 * @param flag
		 * @param param
		 * @return
		 */
		public int callbackTotempletConfig(String id, String obj_id, String param) {
			// TODO Auto-generated method stub
			Map map = new HashMap();
			map.put("id", id);
			map.put("obj_id", obj_id);
			map.put("json_text", param);
			
			int cnt = systemMapper.updateServiceTempletConfig(map);
			String flag = "update";
//			JSONObject json_returnStr = saveAndload(host_name, file_name, flag, param);	
			return cnt;
		}

		public JSONObject saveAndload(String host_name, String file_name, String invokeMethod, String param){
 			String returnStr = "";
			String returnString = "";
			logger.info("content内容为"+param);
			//增|改：http://10.20.112.62:12739/host/:hostname/add/:filename
			//删：http://10.20.112.62:12739/host/:hostname/del/:filename
			//查：http://10.20.112.62:12739/data/hostconfig/:hostname
			//test
 			String getUrl = "http://10.20.112.62:12739/data/hostconfig/";
 			String postUrl = "http://10.20.112.62:12739/host/";
 			//生产
			//http://30.16.11.131/data/hostconfig/SZA-L0022894
 			//String getUrl = "http://30.16.11.131/data/hostconfig/";
 			//String postUrl = "http://30.16.11.131/host/";
			
//			BASE64Decoder decoder = new BASE64Decoder();
//			try {
//				param = new String(decoder.decodeBuffer(param));
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
		    String url = "";
			System.out.println(">>>>>>>>>>>>>>>");
			System.out.println(param);
			System.out.println(">>>>>>>>>>>>>>>");
			try {
				if("get".equals(invokeMethod)){
					param = "";
					url = getUrl+host_name;
					returnStr = sendGet(url,param);
				}else if("add".equals(invokeMethod) || "update".equals(invokeMethod)){
					url = postUrl+host_name+"/add/"+file_name;
					returnStr = sendPost(url,param);
				}else if("del".equals(invokeMethod)){
					url = postUrl+host_name+"/del/"+file_name;
					returnStr = sendPost(url,param);
				}else{
					returnStr = "please put right config param";
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				returnStr = "{  \"msg\": \"failture\",  \"status\": 1,  \"data\": null}";	
				returnStr = e.toString();
			} finally{
				returnString = returnStr;	
			}
			
			System.out.println(">>>>>>>>>>>>>>>");
			System.out.println(returnString);
			System.out.println(">>>>>>>>>>>>>>>");
			JSONObject json_returnStr = new JSONObject();
			json_returnStr = JSONObject.fromObject(returnString);
			
			return json_returnStr;
		}
	
	
	
	    /**
	     * 向指定URL发送GET方法的请求
	     * 
	     * @param url
	     *            发送请求的URL
	     * @param param
	     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	     * @return URL 所代表远程资源的响应结果
	     */
	    public static String sendGet(String url, String param) {
	        String result = "";
	        BufferedReader in = null;
	        try {
	            String urlNameString = url + "?" + param;
	            URL realUrl = new URL(urlNameString);
	            // 打开和URL之间的连接
	            URLConnection connection = realUrl.openConnection();
	            // 设置通用的请求属性
	            connection.setRequestProperty("accept", "*/*");
	            connection.setRequestProperty("connection", "Keep-Alive");
	            connection.setRequestProperty("user-agent",
	                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	            // 建立实际的连接
	            connection.connect();
	            // 获取所有响应头字段
	            Map<String, List<String>> map = connection.getHeaderFields();
	            // 遍历所有的响应头字段
//	            for (String key : map.keySet()) {
//	                System.out.println(key + "--->" + map.get(key));
//	            }
	            // 定义 BufferedReader输入流来读取URL的响应
	            in = new BufferedReader(new InputStreamReader(
	                    connection.getInputStream()));
	            String line;
	            while ((line = in.readLine()) != null) {
	                result += line;
	            }
	        } catch (Exception e) {
	            System.out.println("发送GET请求出现异常！" + e);
	            e.printStackTrace();
	        }
	        // 使用finally块来关闭输入流
	        finally {
	            try {
	                if (in != null) {
	                    in.close();
	                }
	            } catch (Exception e2) {
	                e2.printStackTrace();
	            }
	        }
	        return result;
	    }

	    /**
	     * 向指定 URL 发送POST方法的请求
	     * 
	     * @param url
	     *            发送请求的 URL
	     * @param param
	     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	     * @return 所代表远程资源的响应结果
	     */
	    public static String sendPost(String url, String param) {
	        PrintWriter out = null;
	        BufferedReader in = null;
	        String result = "";
	        try {
	            URL realUrl = new URL(url);
	            // 打开和URL之间的连接
	            URLConnection conn = realUrl.openConnection();
	            // 设置通用的请求属性
	            conn.setRequestProperty("accept", "*/*");
	            conn.setRequestProperty("connection", "Keep-Alive");
	            conn.setRequestProperty("user-agent",
	                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	            // 发送POST请求必须设置如下两行
	            conn.setDoOutput(true);
	            conn.setDoInput(true);
	            // 获取URLConnection对象对应的输出流
	            out = new PrintWriter(conn.getOutputStream());
	            // 发送请求参数
	            out.print(param);
	            // flush输出流的缓冲
	            out.flush();
	            // 定义BufferedReader输入流来读取URL的响应
	            in = new BufferedReader(
	                    new InputStreamReader(conn.getInputStream()));
	            String line;
	            while ((line = in.readLine()) != null) {
	                result += line;
	            }
	        } catch (Exception e) {
	            System.out.println("发送 POST 请求出现异常！"+e);
	            e.printStackTrace();
	        }
	        //使用finally块来关闭输出流、输入流
	        finally{
	            try{
	                if(out!=null){
	                    out.close();
	                }
	                if(in!=null){
	                    in.close();
	                }
	            }
	            catch(IOException ex){
	                ex.printStackTrace();
	            }
	        }
	        return result;
	    }    
	
//	public static void main(String[] args) {
//		String requestUrl = "http://10.20.112.62:12739/data/hostconfig/SZB-L0045555";
//		String requestMethod = "GET";
//		JSONObject httpRequest = httpRequest(requestUrl,requestMethod);
//		System.out.println(httpRequest);
//	}
	
//    public static void main(String[] args) {
////        //发送 GET 请求
////        String sg=sendGet("http://10.20.112.62:12739/data/hostconfig/SZB-L0045555", "");
////        System.out.println(sg);
//        
////        //发送 POST 请求 add
//    	String sa_demo=  "{\"config\":{\" db_host\":\"DB采集host配置,321,Y,请输入主机IP\",\" db_port\":\"DB采集port配置,321,Y,请输入主机端口\",\" db_username\":\"DB采集username配置,213,Y,请输入数据库用户名\",\" db_password\":\"DB采集password配置,3123,Y,请输入数据库密码\",\" db_database\":\"DB采集database配置,312,Y,请输入数据库名称\",\" db_sslmode\":\"DB采集sslmode配置, disable,Y,请输入SSL模式\"},\"frequency\":\"采集频率,60,Y,请输入采集频率\",\"info\":{\"sys_name\":\" HHHHost-ACQ\",\"indextemplateid\":\" 2312321313\",\" obj_name\":\" instance-123\",\" host_name\":\"CNS40009\"},\"type\":\"mysql\",\"Lock\": {}}";
//        //String sa_demo = "{\"action\": \"create\",\"paused\": false,\"running\": -1,\"gathering\": -1,\"firststartsec\": 1491874620,\"laststartsec\": 1493349053,\"lastgathersec\": 1493349053,\"lastcost\": 1,\"readbytes\": 0,\"sentmetrics\": 0,\"filename\": \"XXXXXXXXXXXX.json\",\"type\": \"EXCEPTIONLOG\",\"error\": \"json: cannot unmarshal string into Go value of type []string\",\"frequency\": 60,\"gfrequency\": 6,\"config\": {\"currentlogfiles\": null,\"disablenamefilter\": false,\"encode\": \"\",\"logfiles\": null,\"match\": \"\",\"matchedlogfiles\": null,\"maxread\": 0,\"reallogfiles\": null,\"statoneachfile\": false},\"info\": {},\"Lock\": {}}";
//        
//    	String sa=sendPost("http://10.20.112.62:12739/host/SZB-L0045555/add/XXX", sa_demo);
//    	System.out.println(sa);
//    	
//    	//test last send
////    	String sa_demo=  "{\"config\":{\" db_host\":\"DB采集host配置,123,Y\",\" db_port\":\"DB采集port配置,213,Y\",\" db_username\":\"DB采集username配置,213,Y, \",\" db_password\":\"DB采集password配置,213,Y, \",\" db_database\":\"DB采集database配置,123,Y, \",\" db_sslmode\":\"DB采集sslmode配置,123,Y, \"},\"filename\":\"YYYYY\",\"frequency\":\"采集频率,60,Y,\",\"info\":{\"sys_name\":\" HHHHost-ACQ\",\"indextemplateid\":\"12314123\",\" obj_name\":\" instance-123\",\" host_name\":\"CNS40009\",\"host_name\":\"SZB-L0045555\"},\"type\":\"oracle\"}";
////        String sa=sendPost("http://10.20.112.62:12739/host/SZB-L0045555/add/XXX", sa_demo);
////    	System.out.println(sa);
//        
////        //发送 POST 请求 del
////        String sd=sendPost("http://10.20.112.62:12739/host/SZB-L0045555/del/XXXXXX", "");
////        System.out.println(sd);
//    	
//        //发送 POST 请求 change有点小问题
////        String sa=sendPost("http://10.20.112.62:12739/host/SZB-L0045555/add/XXXX", "{\"action\": \"create\",\"paused\": false,\"running\": -1,\"gathering\": -1,\"firststartsec\": 1491874620,\"laststartsec\": 1493349053,\"lastgathersec\": 1493349053,\"lastcost\": 1,\"readbytes\": 0,\"sentmetrics\": 0,\"filename\": \"XXX.json\",\"type\": \"EXCEPTIONLOG\",\"error\": \"json: cannot unmarshal string into Go value of type []string\",\"frequency\": 60,\"gfrequency\": 6,\"config\": {\"currentlogfiles\": null,\"disablenamefilter\": false,\"encode\": \"\",\"logfiles\": null,\"match\": \"\",\"matchedlogfiles\": null,\"maxread\": 0,\"reallogfiles\": null,\"statoneachfile\": false},\"info\": {\"XXX\":\"XXX\"},\"Lock\": {}}");
////        System.out.println(sa);
////        
////        JSONObject json_returnStr = JSONObject.fromObject(sa);   
////        
////        System.out.println(json_returnStr.get("msg"));
//        
//        
////		//String content = "{\"type\": \"host\",\"frequency\": \"采集频率,60,Y,\",\"config\": {\"cpu\": \"cpu,,false,\",\"mem\": \"mem,,false,\",\"kernel\": \" kernel,,false,\",\"load\": \" load,,true,\",\"io\": \" io,,false,\",\"net\": \" net,,false,\",\"netstat\": \"netstat,,false,\",\"disk\": \"disk,,false,\",\"df\": \" df,,false,\"},\"info\": {\"sys_name\": \"HHHHost-ACQ\",\"indextemplateid\": \"2312321313\",\"obj_name\": \"CNS40009\",\"host_name\": \"CNS40009\"}}";
////        String content = "{cpu=cpu##false#, mem=mem##false# , kernel=kernel##false#, load=load##true#, io= io##false#, net=net##false#, netstat=netstat##false#, disk=disk##false#, df= df## false#}";		
////    	
////		Map<String,Object> contMap = new Gson().fromJson(content, new TypeToken<Map<String,Object>>() {}.getType());
////		
////		System.out.println(String.valueOf(contMap));
//        
//    }

}
